/*
 * @Date: 2025-11-07 18:06:16
 * @Auth: 873768511@qq.com
 * @LastEditors: 873768511@qq.com
 * @LastEditTime: 2025-11-11 14:36:06
 * @FilePath: \corpus\src\pages\systemManagement\menu\hooks\index.ts
 */
import { Form, message } from 'antd';
import { useState } from 'react';
import { createContainer } from 'unstated-next';

import { useRequest } from '@szzj/hooks';

import {
  postMenuCreateCatalog,
  postMenuCreateMenu,
  postMenuDelete,
  postMenuFindWholeTree,
  postMenuSort,
  postMenuUpdateCatalog,
  postMenuUpdateMenu,
} from '@/services/systemManagement/menu';

import { sortMenu } from '../utils';

import type {
  IAppMenuDO,
  ICreateCatalogRequest,
  ICreateMenuRequest,
  ICreOrUpdBtnRequest,
  IUpdateCatalogRequest,
  IUpdateMenuRequest,
} from '@/types/systemManagement/menu';
import { MenuTypeEnum } from '@/types/systemManagement/menu';

export default createContainer(() => {
  const { appCode = '', appName = '' } = {};

  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [editDrawerOpen, setEditDrawerOpen] = useState<boolean>(false);
  const [editingId, setEditingId] = useState<number>();

  const [editFunctionAccessKey, setEditFunctionAccessKey] = useState<string | number>();
  const [form] = Form.useForm<
    IAppMenuDO & { parentName?: string; btnList?: Partial<ICreOrUpdBtnRequest>[] }
  >();

  const postMenuFindWholeTreeRequest = useRequest(
    async () => {
      const res = await postMenuFindWholeTree();
      // 此处直接对 res?.data 进行了 Mutable 操作，需要观察实际影响
      sortMenu(res?.data || []);
      return res?.data || [];
    },
    {
      manual: false,
    },
  );

  const postMenuSortRequest = useRequest(
    async (data) => {
      const res = await postMenuSort({ ...data });
      if (res?.success) {
        message.success('菜单排序成功');
      }
      return res?.data;
    },
    {
      manual: true,
    },
  );

  const postMenuCreateRequest = useRequest(
    async (data: Partial<ICreateMenuRequest | ICreateCatalogRequest>) => {
      const menuType: MenuTypeEnum = form.getFieldValue('menuType');
      if (menuType === MenuTypeEnum.CAT) {
        const res = await postMenuCreateCatalog({
          ...data,
          appCode,
        });
        if (res?.success) {
          postMenuFindWholeTreeRequest.refresh();
          message.success('创建目录成功');
        }
        return res?.success;
      } else if (menuType === MenuTypeEnum.MENU) {
        const res = await postMenuCreateMenu({
          ...data,
          appCode,
        });
        if (res?.success) {
          postMenuFindWholeTreeRequest.refresh();
          message.success('创建菜单成功');
        }
        return res?.success;
      }
      return false;
    },
    {
      manual: true,
    },
  );

  const postMenuUpdateRequest = useRequest(
    async (data: Partial<IUpdateMenuRequest | IUpdateCatalogRequest>) => {
      const menuType: MenuTypeEnum = form.getFieldValue('menuType');
      if (menuType === MenuTypeEnum.CAT) {
        const res = await postMenuUpdateCatalog(data);
        if (res?.success) {
          postMenuFindWholeTreeRequest.refresh();
          message.success('编辑目录成功');
        }
        return res?.success;
      } else if (menuType === MenuTypeEnum.MENU) {
        const res = await postMenuUpdateMenu(data);
        if (res?.success) {
          postMenuFindWholeTreeRequest.refresh();
          message.success('编辑菜单成功');
        }
        return res?.success;
      }
      return false;
    },
    {
      manual: true,
    },
  );

  const postMenuDeleteRequest = useRequest(
    async (id: number, parentId?: number) => {
      const res = await postMenuDelete({ id });
      if (res?.success) {
        postMenuFindWholeTreeRequest.refreshAsync().then((menus) => {
          if (!menus?.find((menu) => menu?.id === parentId)?.children?.length) {
            setExpandedKeys([]);
          }
        });
        message.success('删除成功');
      }
      return res?.data;
    },
    { manual: true },
  );

  return {
    appName,
    form,
    postMenuFindWholeTreeRequest,
    postMenuSortRequest,
    postMenuCreateRequest,
    postMenuUpdateRequest,
    postMenuDeleteRequest,
    expandedKeys,
    setExpandedKeys,
    editDrawerOpen,
    setEditDrawerOpen,
    editingId,
    setEditingId,
    editFunctionAccessKey,
    setEditFunctionAccessKey,
  };
});
